/**
 * 定时任务更新产品名称
 * Created by haoran.shu on 2018/12/5 14:26.
 */
const router = new require('koa-router')();
const logger = require('log4js').getLogger('prod');
const MongoClient = require('mongodb').MongoClient;
const url = require('../config').earecod;
const regexp = new RegExp("[a-zA-Z_]+");
const m = require('../dbs/mongodb');

function productsColl(p) {
  let arr = [];
  for (let pi of p) {
    arr.push({ name: pi });
  }
  return arr;
}

router.get('/reset', async (ctx) => {
  MongoClient.connect(url, {useNewUrlParser: true}).then(client => {
    client.db().collections().then(collections => {
      logger.info('start reset products……');
      let cs = new Set();
      collections.forEach(collection => {
        cs.add(regexp.exec(collection.s.name)[0]);
      });
      m.drop('products').then(() => {
        m.insert('products', productsColl(cs)).then(r => {
          logger.debug(r.result);
          logger.info('reset products success: ' + r.result.n);
        });
      });
      client.close();
    }).catch(() => {
      client.close();
    });

  }).catch(err => {
    logger.error('reset product failed!');
    logger.error(err);
  });
  ctx.body = 'SUCCESS';
});

module.exports = router;
